package logic

import (
	"book_srv/book_srv"
	"book_srv/internal/svc"
	"book_srv/models"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookTabLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookTabLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookTabLogic {
	return &BookTabLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookTabLogic) BookTab(in *book_srv.BookTabRequest) (*book_srv.BookTabResponse, error) {
	// todo: add your logic here and delete this line
	var date []*book_srv.BookFromList
	var books []struct {
		models.Book
		UserName string
	}
	if models.DB.Model(&models.Book{}).Joins("join users on books.user_id = users.id").Select("books.*,users.real_date as user_name join book_tabs on book_tabs.book_id = books.id").Where("book_tabs.user_id = ?", in.UserId).Scan(&books).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}

	for _, book := range books {
		_get := book_srv.BookFromList{
			Title:    book.Title,
			Author:   book.UserName,
			Image:    book.Image,
			AuthorId: book.AuthorId,
		}
		date = append(date, &_get)
	}
	return &book_srv.BookTabResponse{
		Books: date,
	}, nil
}
